package com.thz.system.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class GIFCompressorUtils {
    /**
     * 使用 gifsicle 高效压缩 GIF。保留所有循环、动画帧、透明度，且自动检测环境及参数。
     *
     * @param inputGif 源GIF
     * @param outputGif 输出GIF（可覆盖 inputGif）
     * @param colors 调色板色数 [16~256]
     * @param lossyLevel 失真级别（0~200），0为无损，大于0为有损（文件更小，动画更流畅，推荐20~80）
     * @throws IOException/InterruptedException
     */
    public static void compressGifWithGifsicle(File inputGif, File outputGif, int colors, int lossyLevel) throws IOException, InterruptedException {
        if (!inputGif.exists()) throw new IOException("GIF文件不存在: " + inputGif.getAbsolutePath());
        List<String> cmd = new ArrayList<>();
        cmd.add("gifsicle");
        cmd.add("--no-warnings");
        cmd.add("--colors");
        cmd.add(String.valueOf(colors));
        cmd.add("-O3");
        if (lossyLevel > 0) {
            cmd.add("--lossy=" + lossyLevel);
        }
        cmd.add("--careful");
        cmd.add("--output");
        cmd.add(outputGif.getAbsolutePath());
        cmd.add(inputGif.getAbsolutePath());
        ProcessBuilder pb = new ProcessBuilder(cmd);
        pb.redirectErrorStream(true);
        Process proc = pb.start();
        StringBuilder output = new StringBuilder();
        try (java.io.BufferedReader r = new java.io.BufferedReader(new java.io.InputStreamReader(proc.getInputStream()))) {
            String line;
            while ((line = r.readLine()) != null) output.append(line).append("\n");
        }
        int exit = proc.waitFor();
        if (exit != 0) {
            if (output.toString().contains("not found") || output.toString().contains("not recognized")) {
                throw new IOException("[gifsicle] 未安装, 请先安装 gifsicle (apt/yum/brew/choco 可用)！输出: " + output);
            }
            throw new IOException("gifsicle 压缩失败: " + output);
        }
        log.info("gifsicle 压缩完成: {} → {} colors={} lossy={} 输出:{}字节", inputGif.getAbsolutePath(), outputGif.getAbsolutePath(), colors, lossyLevel, outputGif.length());
    }
}